package main.api;

import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.result.UpdateResult;
import main.GlobalConfig;
import main.ResponseHelper;
import main.StringHelper;
import main.database.AuthorHelper;
import main.database.DatabaseMan;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class AuthorApi {
    @GetMapping ("/api/getauthorlistjson")
    public Map<String, Object> getAuthorListJson(@RequestParam("query") String query) {
        List<String> authorList = AuthorHelper.getAuthorNameList(query);

        Map<String, Object> map = new HashMap<>();
        map.put("result", 200);
        map.put("description", "ok");
        map.put("data", authorList);
        return map;
    }

    @PostMapping("/api/addauthor")
    public ResponseEntity<?> addAuthor(HttpServletRequest request) {
        String author = null, introduction = "";
        Map<String, String[]> map = request.getParameterMap();
        if (map.containsKey("author")) {
            author = map.get("author")[0].trim();
        }
        if (map.containsKey("introduction")) {
            introduction = map.get("introduction")[0].trim();
        }

        String response;
        if (author == null || author.isEmpty()) {
            response = ResponseHelper.createBasicJsonObject(404, "author名字为空或者没有提供").toString();
        }
        else {
            if (AuthorHelper.isAuthorExist(author)) {
                response = ResponseHelper.createBasicJsonObject(404, "同样名字的作者已经存在").toString();
            }
            else {
                String id = AuthorHelper.addAuthor(author, introduction);
                JSONObject jo = ResponseHelper.createBasicJsonObject(200, "ok");
                jo.put("id", id);
                response = jo.toString();
            }
        }

        return ResponseEntity.ok(response);
    }

    @PostMapping("/api/updateauthor")
    public ResponseEntity<?> updateAuthor(HttpServletRequest request) {
        String author = null, introduction = "", id = null;
        Map<String, String[]> map = request.getParameterMap();
        if (map.containsKey("id")) {
            id = map.get("id")[0];
        }
        if (map.containsKey("author")) {
            author = map.get("author")[0].trim();
        }
        if (map.containsKey("introduction")) {
            introduction = map.get("introduction")[0].trim();
        }

        String result;
        if (id == null || id.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "没有对应的作者ID").toString();
        }
        else if (author == null || author.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "作者名字没有提供").toString();
        }
        else if (introduction == null || introduction.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "没有提供作者介绍").toString();
        }
        else {
            MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfAuthor);
            FindIterable<Document> findIterable = collection.find(new BasicDBObject("_id", new ObjectId(id)));
            MongoCursor<Document> cursor = findIterable.iterator();

            if (cursor.hasNext()) {
                Document filter = new Document("_id", new ObjectId(id));
                introduction = StringHelper.replaceReturnWithBR(introduction);
                Document newValue = new Document("name", author).append("introduction", introduction);
                Document updateOperationDocument = new Document("$set", newValue);
                try {
                    UpdateResult updateResult = collection.updateOne(filter, updateOperationDocument);
                    if (updateResult.getModifiedCount() == 1) {
                        result = ResponseHelper.createBasicJsonObject(200, "ok").toString();
                    }
                    else {
                        result = ResponseHelper.createBasicJsonObject(404, "更新数据库出错").toString();
                    }
                }
                catch (Exception e) {
                    result = ResponseHelper.createBasicJsonObject(404, e.toString()).toString();
                }
             }
            else {
                result = ResponseHelper.createBasicJsonObject(404, "没有找到对应ID的作者").toString();
            }
            cursor.close();
        }

        return ResponseEntity.ok(result);
    }

    @PostMapping("/api/getauthorfrompinyin")
    public ResponseEntity<?> getAuthorFromPinYin(HttpServletRequest request) {
        String result;

        String alphabet = "a";
        Map<String, String[]> map = request.getParameterMap();
        if (map.containsKey("key")) {
            String key = map.get("key")[0];
            if (key != null && !key.trim().equals("")) {
                alphabet = key;
            }
        }

        List<String[]> resultList = AuthorHelper.findAuthorFromPinYin(alphabet);

        JSONObject jo = ResponseHelper.createBasicJsonObject(200, "ok");
        jo.put("list", resultList);
        result = jo.toString();
        return ResponseEntity.ok(result);
    }
}
